import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { useTabbarStore } from "../store";
import Home from "@/views/home/index.vue";
import Record from "@/views/record/index.vue";
import Search from "@/views/search/index.vue";
import User from "@/views/user/index.vue";
import Find from "@/views/find/index.vue";
const store = useTabbarStore();
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    name: "Home",
    path: "/home",
    component: Home,
  },
  {
    path: "/record",
    name: "Record",
    component: Record,
  },
  {
    path: "/search",
    name: "Search",
    component: Search,
  },
  {
    path: "/user",
    name: "User",
    component: User,
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/login/index.vue"),
  },
  {
    path: "/register",
    name: "Register",
    component: () => import("@/views/register/index.vue"),
  },
  {
    path: "/shopBag",
    name: "ShopBag",
    component: () => import("@/views/shopBag/index.vue"),
  },
  {
    path: "/address",
    name: "Address",
    component: () => import("@/views/address/index.vue"),
  },
  {
    path: "/confirmOrder",
    name: "ConfirmOrder",
    component: () => import("@/views/confirmOrder/index.vue"),
  },
  {
    path: "/find/:id",
    name: "Find",
    component: Find,
  },
  {
    path: "/details/:id",
    name: "Details",
    component: () => import("@/views/details/index.vue"),
  },
  {
    path: "/userInfo",
    name: "UserInfo",
    component: () => import("@/views/userInfo/index.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  if (localStorage.getItem("token")) {
    const paths = ["/home", "/search", "/record", "/user"];
    const index = paths.findIndex((item) => item === to.path);
    store.active = index;
    next();
  } else {
    store.active = -1;
    if (to.path == "/login" || to.path == "/register") {
      next();
    } else {
      next("/login");
    }
  }
});
export default router;
